#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>

#include "logger.h"

typedef struct data
{

	char sn[64];
	char time[64];
	float temp;
}st_data;
int socket_client_init(char *listen_ip, int listen_port)
{

	struct sockaddr_in      servaddr;
	int                     rv = 0;
	int                     listenfd;
	
	if( !listen_ip||!listen_port )
	{
		log_error("ERROR: Invalid input arguments\n");//无效的参数
		return -1;
	}
        listenfd=socket(AF_INET, SOCK_STREAM, 0);

	if(listenfd < 0)
	{
		log_error("Create listenfd[%d] failure:%s\n", listenfd, strerror(errno));

		return -1;
	}
	log_info("Create listenfd[%d] successfully!\n", listenfd);

	memset(&servaddr, 0, sizeof(servaddr));

	servaddr.sin_family        = AF_INET;
	servaddr.sin_port          = htons(listen_port);//将16位主机字节序转换为网络字节序（大端字节序）端口号是16位的
        inet_aton(listen_ip, &servaddr.sin_addr);

	if( connect( listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0)
	{
         	log_error("connect to socket failure:%s\n", strerror(errno));
		return -2;
		close(listenfd);
	}
	
        return listenfd;

}
int socket_send_data (int fd, st_data *send_data)
{

	int                 i;
	char                wbuff[1024];

        snprintf(wbuff, sizeof(wbuff),"%s/%s/%2.2f\n", send_data->sn, send_data->time, send_data->temp);

	if(write(fd, wbuff, sizeof(wbuff)) < 0)//wt_buf 存放的是客户端储存在数据库的数据
	{
		log_error("error: write data to listenfd[%d] failure:%s\n!", fd, strerror(errno));
		close(fd);
	}
	log_info("Sucess to send data:%s\n", wbuff);
	return 0;
}

int socket_close(int * sockfd)
{
	if(sockfd==NULL)
	{
		return -1;
	}
	if(*sockfd>0)
	{
		close(*sockfd);
		*sockfd=-1;
	}
	return 0;
}

